package com.muc.handler;

import com.muc.entity.AdminDO;
import com.muc.service.AdminService;
import com.muc.service.impl.AdminServiceImpl;
import com.muc.view.LoginView;
import com.muc.view.MainView;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class LoginHandler extends KeyAdapter implements ActionListener {
    private LoginView loginView;
    private MainView mainView;//不初始化 jjj
    public LoginHandler(LoginView loginView,MainView mainView)
    {
        this.loginView = loginView;
        this.mainView = mainView;//jjj

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton jButton = (JButton) e.getSource();
        String text = jButton.getText();
        if("重置".equals(text)){
            loginView.getUserTxt().setText("");
            loginView.getPwdField().setText("");

        }else if("登录".equals(text)){//需要使用数据库 使用服务器try try
            //
            login();
        }
    }

    private void login() {
        String user = loginView.getUserTxt().getText();
        char[] passwordC = loginView.getPwdField().getPassword();
        if(user==null || "".equals(user.trim())
                ||passwordC==null){
            JOptionPane.showMessageDialog(loginView,"用户名密码必填");
            return;
        }
        String pwd = new String(passwordC);
        System.out.println(user+":"+pwd);

        //查询db
        AdminService adminService = new AdminServiceImpl();
        AdminDO adminDO = new AdminDO();
        adminDO.setUserName(user);
        adminDO.setPwd(pwd);
        boolean flag = adminService.validateAdmin(adminDO);
        if(flag){
            //登录成功的话，跳转到主界面并销毁登录界面
//            mainView = new MainView();
            mainView.setVisible(true);
            loginView.dispose();
        }else {
            JOptionPane.showMessageDialog(loginView,"用户名密码错误");
        }
    }

    //回车键实现登录效果
    @Override
    public void keyPressed(KeyEvent e) {
        if(KeyEvent.VK_ENTER == e.getKeyCode()){
            login();
        }
    }
}
